import axios from 'axios'

// 作业服务基础URL
const HOMEWORK_API_BASE_URL = 'http://localhost:9100'

/**
 * 作业管理API
 */
export const homeworkAPI = {
  /**
   * 获取指定作业的所有提交记录
   */
  getHomeworkSubmissions(homeworkId) {
    return axios.get(`${HOMEWORK_API_BASE_URL}/api/teacher/homework/${homeworkId}/submissions`)
  },

  /**
   * 获取学生提交的作业文件列表
   */
  getSubmissionFiles(submitId) {
    return axios.get(`${HOMEWORK_API_BASE_URL}/api/teacher/homework/submission/${submitId}/files`)
  },

  /**
   * 获取文件下载链接
   */
  getFileDownloadUrl(fileId) {
    return axios.get(`${HOMEWORK_API_BASE_URL}/api/teacher/homework/file/${fileId}/download`)
  },

  /**
   * 批量获取文件下载链接
   */
  batchDownloadFiles(fileIds) {
    return axios.post(`${HOMEWORK_API_BASE_URL}/api/teacher/homework/files/batch-download`, {
      fileIds: fileIds
    })
  },

  /**
   * 直接下载文件
   */
  downloadFile(fileId) {
    return `${HOMEWORK_API_BASE_URL}/api/files/download/${fileId}`
  },

  /**
   * 获取作业列表（教师端）
   */
  getHomeworkList(classId, params = {}) {
    return axios.get(`${HOMEWORK_API_BASE_URL}/api/homework/class/${classId}`, {
      params: {
        page: params.page || 0,
        size: params.size || 10,
        sortBy: params.sortBy || 'createTime',
        sortDir: params.sortDir || 'desc'
      }
    })
  }
}

/**
 * 文件下载工具
 */
export const downloadUtils = {
  /**
   * 通过URL直接下载文件
   */
  downloadByUrl(url, fileName) {
    const link = document.createElement('a')
    link.href = url
    link.download = fileName || '下载文件'
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },

  /**
   * 批量下载文件
   */
  async batchDownload(fileIds) {
    try {
      const response = await homeworkAPI.batchDownloadFiles(fileIds)
      if (response.data.code === 200) {
        const downloadInfo = response.data.data
        
        // 依次下载每个文件
        downloadInfo.forEach((file, index) => {
          setTimeout(() => {
            this.downloadByUrl(file.downloadUrl, file.fileName)
          }, index * 1000) // 每秒下载一个文件，避免浏览器限制
        })
        
        return { success: true, count: downloadInfo.length }
      } else {
        throw new Error(response.data.message || '获取下载链接失败')
      }
    } catch (error) {
      console.error('批量下载失败:', error)
      throw error
    }
  },

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }
}

export default {
  homeworkAPI,
  downloadUtils
}
